<template>
	<view>
		<!-- 顶部导航栏 -->
		<view class="flex padding justify-between fixed-nav" style="padding-top: 100upx;">
			<!-- 返回键 -->
			<image 
				src="/src/static/zr/back.png" 
				mode="" style="height: 60upx; width: 60upx;"
				@click="handleback"
			>
			</image>
			<view class="text-xl text-black">动态详情</view>
			<view class="iconfont icon-gengduo4" style="height: 60upx; width: 60upx;"></view>
		</view>
		<!-- 占位 -->
		<view class="nav-placeholder"></view>
		
		<!-- 博主信息区 -->
		<view class="flex details_writer margin-top justify-between">
			<view class="flex">
				<!-- 头像 -->
				<image :src="detail_data?.authorAvatar" mode="" class="cu-avatar round"></image>
				<view class="">
					<view class="flex margin-left">
						<!-- 作者姓名 -->
						<view class="text-lg">{{detail_data?.author}}</view>
						<!-- 作者头衔 -->
						<view class="cu-tag round bg-purple light" style="margin-top: -5upx;">
							<image src="/src/static/zr/jinxuan.png" mode="" class="jinxuan"></image>
							<view class="">{{detail_data?.authorTitle}}</view>
						</view>
					</view>
					<view class="flex margin-left" style="margin-top: 5upx;">
						<view class="text-sm text-gray">发布至</view>
						<view class="text-sm">{{detail_data?.tag}}</view>
					</view>
				</view>
			</view>
			
			<!-- 关注按键 -->
			<view class="" style="margin-right: 20upx;">
				<button class="cu-btn bg-black">+关注</button>
			</view>
			
		</view>
		
		<!-- 正文内容区 -->
		<view class="">
			<!-- 标题 -->
			<view class="flex margin-top-sm margin-left">
				<view class="text-mauve text-lg">心岛精选 | </view>
				<view class="text-black text-lg margin-left-sm">{{detail_data?.title}}</view>
			</view>
			
			<!-- 正文 -->
			<view class="margin-top-sm content-text">
				{{detail_data?.detail.content}}
			</view>
		</view>
		
		<!-- 发布日期 -->
		<view class="flex justify-end">
			<view class=" margin-right text-gray">{{detail_data?.detail.publishTime}}</view>
		</view>
		
		<!-- 淡色分隔线 -->
		<view class="divider"></view>
		
		<!-- 评论区 -->
		<view class="">
			<!-- 转发评论喜欢各种数据 -->
			<view class="flex margin-top-sm" style="margin-left: 20upx;">
				<view class="text-gray margin-left">转发</view>
				<view class="text-black margin-left">评论{{detail_data?.detail.interactions.commentCount}}</view>
				<view class="text-gray margin-left">喜欢</view>
			</view>
		</view>
		
		<!-- 评论区主体 -->
		<view class="" v-for="(item,index) in detail_data?.detail.comments">
			<view class="flex justify-between" >
				<view class="flex margin-top">
					<!-- 头像 -->
					<image :src="item.userAvatar" mode="" class="cu-avatar round margin-left "></image>
					
					
					<view class="margin-left" style="margin-top: -10upx;">
						<!-- 评论人的姓名 -->
						<view class="text-gray">{{item.user}}</view>
						<!-- 评论人的内容 -->
						<view class="" style="margin-top:5upx; margin-bottom: 9upx; width: 550upx;">{{item.content}}</view>
						<!-- 评论时间 -->
						<view class="text-gray text-sm">{{item.time}}</view>
					</view>
				</view>
				<!-- 点赞爱心 -->
				<view class="margin-right">
					<view class="flex justify-center">
						<view
							class="iconfont icon-xihuan2 margin-top" 
							@click="handlelike(index)"
							 :class="{ 'liked': likesStatus[index] }"
						>
						</view>
					</view>
					
					
					<view class="flex justify-center" >
						<text>{{item.likeCount}}</text>
					</view>
				</view>
			</view>
			<!-- 淡色分隔线 -->
			<view class="divider"></view>
		</view>
		
		
		
		
		
		<!-- 没有更多啦 -->
		<view class="flex justify-center" style="height: 300upx;">
			<view class="text-gray" style="margin-top: 50upx;">已经到底啦~</view>
		</view>
		
		
		<!-- 发表评论区 -->
		<view class="cu-bar foot bg-white flex">
			<!-- 发表评论 -->
			
				<!-- <text class="cuIcon-creative"></text> -->
				<!-- 发表评论 -->
				<!-- <input type="text" class="" v-model="commentContent" maxlength="100"/> -->
				
				<textarea
				  v-model="commentContent"
				  
				  auto-height  
				  class="auto-height-textarea"
				  placeholder="请输入内容..."
				  
				></textarea>

			
			
			
			<view class="margin-top flex" style="width: 250upx;" v-if="!isshow_btn_send">
				<!-- 转发 -->
				<view class="iconfont icon-fenxiang5 flex margin-left-sm" style="height: 60upx; width: 60upx;">
					<view class="text-gray text-sm">{{detail_data?.detail.interactions.forward}}</view>
				</view>
				<!-- 评论 -->
				<view class="iconfont  icon-xiaoxi-zhihui flex margin-left-sm" style="height: 60upx; width: 60upx;">
					<view class="text-gray text-sm">{{detail_data?.detail.interactions.commentCount}}</view>
				</view>
				<!-- 点赞爱心 -->
				<view 
					class="iconfont icon-xihuan2 flex margin-left-sm" 
					style="height: 60upx; width: 60upx;"
					@click="handle_text_like"
					:class="{'liked' : text_like}"
				>
					<view class="text-gray text-sm">{{detail_data?.detail.interactions.likeCount}}</view>
				</view>
				
			</view>
			<view class=" flex" style="width: 250upx; margin-left: 50upx;">
				<button 
					class="cu-btn round bg-mauve" 
					style="height: 60upx; width: 150upx;" 
					v-if="isshow_btn_send"
					@click="handle_Send"
				>
					发送
				</button>
			</view>
			
		</view>
		
		
		
	</view>
	
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app';
import { ref, watch, type Ref } from 'vue';
import type {Article, LikePerson,Comment} from '@/model/Dynamics'
import { useArticleStore } from '@/store/heartcart_details';
import {likePost, 
		unlikePost, 
		addPostLikePerson, 
		removePostLikePerson, 
		likeComment, 
		unlikeComment,
		addCommentLikePerson,
		removeCommentLikePerson
		} 
		from '@/api/heartisland_details'
import {send_comment} from '@/api/send'
import { useAccount } from '@/store/user'


interface UserData{
		username:string,
		objectID:string
	}
	
	// 从状态机中获取数据
	const useStore = useAccount()
	const articleStore = useArticleStore();
	
	
	const detail_data:Ref<Article | null> = ref(null)
	// 记录每个评论的点赞状态
	const likesStatus: Ref<Record<number, boolean>> = ref({});
	// 记录文章点赞状态
	const text_like:Ref<boolean> = ref(false)
	
	
	const load_like_list = ()=>{
		// 初始化评论区点赞状态（基于实际数据）
		detail_data.value?.detail.comments.forEach((comment, index) => {
		// 获取当前登录用户ID（用于判断是否点赞）
		 const currentUserId = useStore.userinfo?.objectId;
		  // 如果用户已登录且评论有点赞人列表
		  if (currentUserId && comment.likeperson && comment.likeperson.length > 0) {
		    // 检查当前用户是否在点赞人列表中
			
		    const hasLiked = comment.likeperson.some(
		      (person: LikePerson) => person.objectID === currentUserId
		    );
		    likesStatus.value[index] = hasLiked;
		  } 
		  else {
		    // 未登录或无点赞数据时默认未点赞
		    likesStatus.value[index] = false;
		  }
		});
	}
	
	onLoad( () => {
		// 从pinia里面获取数据
		detail_data.value = articleStore.currentArticle;
	   // 初始化评论区点赞状态（基于实际数据）
	    load_like_list()
	    
		
		
		// 同时检查用户是否给该文章点赞
		const currentLikes:LikePerson[] = detail_data.value?.detail.likeperson!;
		text_like.value = currentLikes.some(item => item.objectID === useStore.userinfo?.objectId)
	});
	
	
	
	// 返回上一级
	const handleback = ()=>{
		uni.reLaunch({
			url:"/pages/HeartIsland/index"
		})
	}
	// 评论区点赞爱心
	const handlelike = async (index: number)=>{
		if (!detail_data.value || !useStore.userinfo?.objectId){
			show_login()
			
			return;
		} 
			// 获取用户信息（方便后续存入数据库）
			const user_data:UserData =  {
				username:useStore.userinfo?.name!,
				objectID:useStore.userinfo?.objectId!
			}
			//进行点赞状态更新 
			const isLiked = likesStatus.value[index];
			likesStatus.value[index] = !isLiked;
			// 更新评论区点赞数
			const currentComment = detail_data.value.detail.comments[index];
			// 进行判断状态
			if(isLiked){
				currentComment.likeCount = currentComment.likeCount - 1
				// 进行数据库更新
				await unlikeComment(detail_data.value.objectId, index)
				await removeCommentLikePerson(detail_data.value.objectId, index, user_data)
			}
			else{
				currentComment.likeCount = currentComment.likeCount + 1
				// 进行数据库更新
				await likeComment(detail_data.value.objectId, index)
				
				await addCommentLikePerson(detail_data.value.objectId, index, user_data)
			}
	}
	
	// 文章点赞爱心
	const handle_text_like = async ()=>{
		if (!detail_data.value || !useStore.userinfo?.objectId){
			// 展示没有登录的弹窗
			show_login()
			return;
		} 
		// 获取用户信息（方便后续存入数据库）
		const user_data:UserData =  {
			username:useStore.userinfo?.name!,
			objectID:useStore.userinfo?.objectId!
		}
		
		text_like.value = !text_like.value
		// 更新文章点赞爱心数量
		const interactions = detail_data.value.detail.interactions;
			if (text_like.value) {
				interactions.likeCount ++
				// 进行数据库更新
				await likePost(detail_data.value.objectId)    //更新点赞数据
				await addPostLikePerson(detail_data.value, user_data)
			} 
			else {
				interactions.likeCount --
				// 进行数据库更新
				await unlikePost(detail_data.value.objectId)    //更新点赞数据
				await removePostLikePerson(detail_data.value, useStore.userinfo.objectId)
			
			}
		
	}
	
	// 暂无登录弹窗
	const show_login=()=>{
		uni.showModal({
			title:'暂没登录，请登录后再进行此操作',
			confirmColor:'#F37B1D',
			content:'是否跳转到登录界面？',
			success: ({confirm}) => {
				if(confirm){
					uni.navigateTo({
						url:'/pages/TreeHole/login'
					})
				}
			}
		})
	}
	
	// 以下为发表评论的内容
	
	// 获取时间戳
	const formatCommentTime = (date: Date = new Date()): string => {
	  // 获取年、月、日（确保两位数）
	  const year = date.getFullYear();
	  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需+1
	  const day = String(date.getDate()).padStart(2, '0');
	  
	  // 获取小时、分钟（确保两位数）
	  const hours = String(date.getHours()).padStart(2, '0');
	  const minutes = String(date.getMinutes()).padStart(2, '0');
	  
	  // 拼接为目标格式
	  return `${year}-${month}-${day} ${hours}:${minutes}`;
	};
	
	const commentContent:Ref<string> = ref('')
	const isshow_btn_send:Ref<boolean> = ref(false)
	
	const send = ()=>{
		
		isshow_btn_send.value = true
		
	}
	watch(
		() => commentContent.value.trim(), // 监听处理后的内容（去除首尾空格）
		(newVal) => {
			// 有内容则显示按钮，空则隐藏
			isshow_btn_send.value = newVal.length > 0;
		}
	)
	const  comment_data:Ref<Comment | null > = ref(null)
	// 点击发送后上传数据库进行提交
	const handle_Send = async()=>{
		if (!detail_data.value || !useStore.userinfo?.objectId){
			// 展示没有登录的弹窗
			show_login()
			return;
		} 
		comment_data.value = {
			user:useStore.userinfo?.name!,
			userAvatar:useStore.userinfo?.avatar!,
			userId:useStore.userinfo?.objectId!,
			time:formatCommentTime(),
			likeCount: 0,
			replyCount: 0,
			replies: [],
			likeperson:[],
			content:commentContent.value
		}
		try{
			 await send_comment(detail_data.value.objectId, comment_data.value)
			 uni.showToast({ title: '评论发表成功', icon: 'none' });
			 // 更新数据
			 if (detail_data.value && detail_data.value.detail.comments) {
				 detail_data.value.detail.comments.push(comment_data.value);
				 load_like_list()
			 }
			 
		}
		catch(error){
			console.error('评论发表失败：', error);
			uni.showToast({ title: '评论发表失败', icon: 'none' });
		}
		
	}
	
</script>

<style lang="scss">
	page{
		background-color: white;
		/* 避免页面内容被固定导航栏遮挡 */
		padding-top: 0; 
	}
	.details_writer{
		image{
			margin-left: 20upx;
			height: 80upx;
			width: 80upx;
		}
		.jinxuan{
				height: 25upx;
				width: 25upx;
				margin-left: 0upx;
		}
	}
	
	.fixed-nav {
			/* 固定定位在顶部 */
			position: fixed; 
			top: 0;
			left: 0;
			right: 0;
			/* 导航栏高度（根据内容调整） */
			height: 150upx; 
			/* 背景色（避免透明导致内容穿透） */
			background-color: white; 
			/* 层级设置为最高，避免被其他元素覆盖 */
			z-index: 999; 
			/* 原有的padding-top保持不变 */
			padding-top: 30upx; 
		}
		
	/* 新增：占位元素，抵消固定导航栏的高度，防止内容上移 */
	.nav-placeholder {
		height: 140upx; /* 与导航栏高度一致 */
	}
   
   // 正文样式
   .content-text {
     white-space: pre-line; /* 保留换行和空格，自动处理多余空白 */
     line-height: 1.8; /* 增加行高，提升可读性 */
     padding: 15upx;
   }
   
   // 底部导航栏发表评论
   .foot{
	   background-color: white;
   }
   
   /* 淡色分隔线样式 */
   .divider {
   	
   	width: 95%; /* 线长略短于卡片宽度，更美观 */
   	margin: 10upx auto; /* 上下留白，居中显示 */
   	margin-top: 40upx;
   	border-top: 1px solid #eee; /* 浅灰色线条 */
   }
   
   // 点赞样式
   .icon-xihuan2.liked {
	 color: #ff4d4f; /* 红色 */
	 animation: like 0.3s ease;
   }
   @keyframes like {
     0% { transform: scale(1); }
     50% { transform: scale(1.3); }
     100% { transform: scale(1); }
   }
   
   .auto-height-textarea {
     /* 初始高度为一行（根据字体大小调整） */
     min-height: 40upx; 
     /* 可选：限制最大高度，超出后不再撑开（避免过高） */
     max-height: 200upx;
     
     /* 隐藏滚动条（兼容各平台） */
     overflow: hidden; /* 核心：内容撑开时不显示滚动条 */
     margin-left: 10upx;
	 padding-bottom: 20upx; 
     /* 其他样式优化 */
     width: 100%;
     padding: 15upx;
     font-size: 28upx;
     line-height: 1.5; /* 确保行高正常，避免内容拥挤 */
     border: 1px solid #eee;
     border-radius: 8upx;
    
   }
</style>
